<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab1" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="all" v-if="mallOrdersForAll">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="销售订单号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="商城订单号：">
          <el-input v-model="listQuery.mallSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="采购订单号：">
          <el-input v-model="listQuery.purchaseOrderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单时间：">
          <el-date-picker
            v-model="listQuery.orderTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            v-if="listQuery.tab1 == 'my'"
            @click="banding('more')"
            type="primary">
            批量绑定
          </el-button>
          <el-button
            v-if="listQuery.tab1 == 'my'"
            @click="moreOrder()"
            type="success">
            批量下采购订单（{{tableData | fifchoose}}）
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div>
      <el-radio-group v-model="listQuery.tab2" size="small" @change="handleSearchList()">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="unBindMaLLOrder">未绑定商城订单</el-radio-button>
        <el-radio-button label="unBindPurchaseOrder">已绑定商城订单未下采购单</el-radio-button>
        <el-radio-button label="hasBindPurchaseOrder">已绑定商城订单已下采购单</el-radio-button>
      </el-radio-group>
    </div>
    <div class="table-container">
      <el-table
        :header-cell-style="{'text-align':'center'}"
        v-loading="listLoading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        :span-method="objectSpanMethod"
        style="width: 100%; margin-top: 20px">
        <el-table-column type="selection" width="60" align="center" :selectable="checkSelectable"></el-table-column>
        <el-table-column
          prop="orderSn"
          align="center"
          label="销售订单号"
          min-width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="orderTime"
          label="订单时间"
          min-width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="customerName"
          label="客户名称"
          min-width="200">
        </el-table-column>
        <el-table-column
          prop="userName"
          label="销售员"
          min-width="100"
          align="center">
        </el-table-column>
        <el-table-column
          align="center"
          prop="goodsSn"
          label="品类牌号"
          min-width="200">
        </el-table-column>
        <el-table-column
          align="center"
          prop="goodsNum"
          label="合同数量"
          min-width="100">
        </el-table-column>
        <el-table-column  prop="sendType" label="提货方式" min-width="150" align="center">
        </el-table-column>

        <el-table-column
          prop="addressInfo"
          label="送到地址"
          min-width="200"
          align="center">
        </el-table-column>
        <el-table-column
          prop="orderNoticeTip"
          label="特殊要求"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="orderRemark"
          label="合同备注"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mallSn"
          label="商城订单号"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mallAmount"
          label="商城订单总价"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mallGoodsNum"
          label="汇总数量"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mallAveragePrice"
          label="商城订单单价"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="purchaseSn"
          label="采购订单号"
          min-width="150"
          align="center">
        </el-table-column>
        <el-table-column
          v-if="listQuery.tab1 == 'my'"
          label="绑定/解绑"
          min-width="100"
          fixed="right"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="banding('one',scope.row)" size="mini" v-if="scope.row.mallSn == ''">绑定</el-button>
            <el-button type="text" @click="unBanding(scope.row)" size="mini" v-else>解绑</el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="listQuery.tab1 == 'my'"
          label="操作"
          prop="setting"
          min-width="120"
          fixed="right"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="toOrder(scope.row)" size="mini" v-if="scope.row.purchaseSn == '' && scope.row.mallSn != ''">下采购订单</el-button>
            <el-checkbox v-model="scope.row.isChoose" v-if="scope.row.purchaseSn == '' && scope.row.mallSn != ''">批量采购单</el-checkbox>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      title="绑定"
      :beforeClose="handleClose"
      :visible.sync="show"
      width="400px">
      <el-form :model="form" size="mini" label-width="120px" :rules="rules" ref="form">
        <el-form-item label="商城订单号：" prop="mallSn">
          <el-input  v-model="form.mallSn" clearable @change="changeMallSn"></el-input>
        </el-form-item>
        <el-form-item label="商城订单总价：" prop="mallAmount">
          <el-input  v-model="form.mallAmount" type="number" clearable></el-input>
        </el-form-item>
        <div style="font-size:14px;color:red;line-height: 20px" v-if="oldMallAmount !== ''">此商城订单号已被绑定，原商城订单总价为<span style="padding:0 2px;font-weight: bold">{{oldMallAmount}}</span>。订单总价修改后将会直接覆盖原价格，无需修改请保持原价不变</div>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getOrderUsersList,supplierList} from '@/api/partner'
import {mallOrderList,mallOrderOperate,mallSnInfo} from '@/api/allInLine/inquiry'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
import {validateCommission} from '@/utils/validate';

const defaultListQuery={
  'tab1':'my',
  'tab2':'all',//(unBindMaLLOrder-未绑商城订单，unBindPurchaseOrder-未绑采购订单,hasBindPurchaseOrder-已绑采购订单)
  "orderSn" : "", // 订单号
  "mallSn" : '', //供应商ID
  "purchaseOrderSn" : '', //采购员ID
  "orderTime" : [],// 申请状态(0审核中，10已通过，20已拒绝)
  "pageNum" : 1,
  "pageSize" : 10
};
const defaultForm = {
  "moId" : '',
  "operateType" : "bindMallOrder",//绑定商城订单
  "mallSn" : "",   //商城订单号
  "mallAmount" : ''  //商品订单总价
};
export default {
  name: "purchaseAfterSettlement",
  data(){

    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      userOptionList:[],
      roles:store.getters.roles ? store.getters.roles : [],


      multipleSelection:[],
      form: JSON.parse(JSON.stringify(defaultForm)),
      show:false,
      btnLoading:false,
      rules:{
        mallSn:[{required: true, trigger: 'blur' ,message: '此项必填'}],
        mallAmount:[{required: true, trigger: 'blur' ,message: '此项必填'}],
      },
      oldMallAmount:''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
    mallOrdersForAll (){
      if(this.roles.indexOf("mallOrdersForAll") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.getList();
    this.getUserOptionList();
    this.getSupplierList()
  },
  filters: {
    fifchoose(list) {
      let choose = list.filter(item => {
        return item.isChoose == true
      })
      return choose.length
    }

  },
  methods:{
    moreOrder(){
      let choose =  this.tableData.filter(item => {
        return item.isChoose == true
      })
      if(choose.length == 0){
        this.$message.warning('请选择要下采购单的记录')
        return false
      }
      let mallSn = choose.map(item => {
        return item.mallSn
      })
      this.$router.push({
        name:'addPurchaseOrder',
        query:{
          mallSn:mallSn.join(",")
        }
      })
    },
    changeMallSn(){
      this.oldMallAmount = ''
      mallSnInfo({mallSn:this.form.mallSn}).then((res)=>{
        this.oldMallAmount = res.list[0].mallAmount ? res.list[0].mallAmount : ''
        this.form.mallAmount = res.list[0].mallAmount ? res.list[0].mallAmount : ''
      })
    },
    //关闭
    handleClose(){
      this.show = false;
    },

    //提交
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.form));
          this.btnLoading = true;
          mallOrderOperate(data).then((res)=>{
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.btnLoading = false;
            this.getList();
            this.handleClose();
          }).catch(()=>{
            this.btnLoading = false
          })
        }
      })
    },
    //绑定
    banding(type,row){
      if(type == 'one'){
        this.show = true
        this.form =  JSON.parse(JSON.stringify(defaultForm))
        this.form.moId = row.moId
      }else if(type == 'more'){
         if(this.multipleSelection.length == 0){
           this.$message({
             message: '请选择要操作的记录',
             type: 'warning',
             duration: 1000
           });
         }else {
           let propertyValues = new Set(this.multipleSelection.map(item => item.sapGoodsId));
           let moId = this.multipleSelection.map(item => item['moId'])
           let allSameProperty = propertyValues.size === 1; //商品牌号相同
           if (allSameProperty) {
             this.show = true
             this.form =  JSON.parse(JSON.stringify(defaultForm))
             this.form.moId = moId.join(",")
           }else{
             this.$message({
               message: '请选择牌号相同的订单进行批量绑定',
               type: 'warning',
               duration: 1000
             });
           }
         }
      }
    },
    //解绑
    unBanding(row){
      mallOrderOperate({moId:row.moId,operateType:'unBindMallOrder'}).then(()=>{
          this.$message({
            message: '解绑成功',
            type: 'success',
            duration: 1000
          });
          this.getList()
      })
    },

    toOrder(row){
       this.$router.push({
        name:'addPurchaseOrder',
        query:{
          mallSn:row.mallSn
        }
      })
    },
    //判断是否能选择
    checkSelectable(row, index){
      return row['mallSn'] == ''
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let prop = ['mallSn','mallAmount','mallAveragePrice','mallGoodsNum','purchaseSn','setting']
      if(prop.indexOf(column.property) != -1){
        if (row.isrowspan) {
          return {
            rowspan: row.rowNum,
            colspan: 1
          };
        }else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    //多选表格项
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //供应商
    getSupplierList() {
      supplierList().then((res)=>{
        this.options2 = res;
      })
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({departmentId:3,status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },


    /**
     * 切换选择状态
     */
    handleSelect(key, keyPath){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab1 = key;
      this.handleSearchList();
    },
    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取订单列表
    getList() {
      this.listLoading = true;
      mallOrderList(this.listQuery).then(response => {
        let list = []
        response.list.forEach((el,index)=>{
          el.detailList.forEach((ee,index2)=>{
            list.push({
              mallAmount:el.mallAmount,
              mallAveragePrice:el.mallAveragePrice,
              mallGoodsNum:el.mallGoodsNum,
              mallSn:el.mallSn,
              moSn:el.moSn,
              moId:el.moId,
              purchaseSn:el.purchaseSn,
              addressInfo:ee.addressInfo,
              customerName:ee.customerName,
              goodsNum:ee.goodsNum,
              goodsSn:ee.goodsSn,
              orderId:ee.orderId,
              orderNoticeTip:ee.orderNoticeTip,
              orderRemark:ee.orderRemark,
              orderSn:ee.orderSn,
              orderTime:ee.orderTime,
              sapGoodsId:ee.sapGoodsId,
              sendType:ee.sendType,
              userName:ee.userName,
              isrowspan: index2 == 0  ? true : false,
              rowNum:el.detailList.length,
              isChoose:false
            })
          })
        })
        this.tableData = list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },

  },
}
</script>

<style scoped lang="scss">

</style>
